package com.gizwits.opensource.appkit.ControlModule;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import java.util.concurrent.ConcurrentHashMap;

import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.gizwits.opensource.appkit.CommonModule.GosDeploy;
import com.gizwits.opensource.appkit.R;
import com.gizwits.opensource.appkit.yasystem.Kind;
import com.gizwits.opensource.appkit.yasystem.Main1Activity;
import com.gizwits.opensource.appkit.yasystem.Main2Activity;
import com.gizwits.opensource.appkit.yasystem.Main3Activity;
import com.gizwits.opensource.appkit.yasystem.MainActivity;
import com.gizwits.opensource.appkit.yasystem.Secend1Activity;
import com.gizwits.opensource.appkit.yasystem.SecendActivity;
import com.gizwits.opensource.appkit.yasystem.Second2Activity;
import com.gizwits.opensource.appkit.yasystem.Second3Activity;

public class GosDeviceControlActivity extends GosControlModuleBaseActivity
		implements OnClickListener, OnEditorActionListener {

	/** 设备列表传入的设备变量 */
	private static GizWifiDevice mDevice;
    Intent intent;
	private IntentFilter intentFilter;
	private LocalBroadcastManager localBroadcastManager;
	private LocalReceiver localReceiver;
	private Button btn_SheE;
	private Button btn_SyaE;
	private Button btn_skip;
	private Button btn_SonestartE;
	private Button btn_SkindE;
	private TextView tv_data_STATE;
	private TextView tv_data_kind;
	private TextView tv_data_wan;
	private TextView tv_data_hetime;
	private RelativeLayout r1,r2;
	private enum handler_key {

		/** 更新界面 */
		UPDATE_UI,

		DISCONNECT,
	}

	private Runnable mRunnable = new Runnable() {
		public void run() {
			if (isDeviceCanBeControlled()) {
				progressDialog.cancel();
			} else {
				toastDeviceNoReadyAndExit();
			}
		}

	};

	/** The handler. */
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			handler_key key = handler_key.values()[msg.what];
			switch (key) {
			case UPDATE_UI:
				updateUI();
				break;
			case DISCONNECT:
				toastDeviceDisconnectAndExit();
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gos_device_control);
		initDevice();
		setToolBar(true, getDeviceName());
		final Drawable add = getResources().getDrawable(R.drawable.common_setting_more);
		int color = GosDeploy.appConfig_Contrast();
		add.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
		mToolbar.setOverflowIcon(add);
		initView();
		initEvent();
	}

	private void initView() {
		btn_skip = (Button) findViewById(R.id.skip);
		r1 = (RelativeLayout) findViewById(R.id.r1);
		btn_SheE = (Button) findViewById(R.id.btn_SheE);
		btn_SyaE = (Button) findViewById(R.id.btn_SyaE);
		btn_SonestartE = (Button) findViewById(R.id.btn_SonestartE);
		btn_SkindE = (Button) findViewById(R.id.btn_SkindE);
		tv_data_STATE = (TextView) findViewById(R.id.tv_data_STATE);
		tv_data_kind = (TextView) findViewById(R.id.tv_data_kind);
		tv_data_wan = (TextView) findViewById(R.id.tv_data_wan);
		tv_data_hetime = (TextView) findViewById(R.id.tv_data_hetime);

	}

	private void initEvent() {
		btn_skip.setOnClickListener(this);
		localBroadcastManager = LocalBroadcastManager.getInstance(this);
		btn_SheE.setOnClickListener(this);
		btn_SyaE.setOnClickListener(this);
		btn_SonestartE.setOnClickListener(this);
		btn_SkindE.setOnClickListener(this);
		intentFilter = new IntentFilter();
		intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");
		localReceiver = new LocalReceiver();
		localBroadcastManager.registerReceiver(localReceiver,intentFilter);

		r1.setVisibility(View.INVISIBLE);

	
	}

	private void initDevice() {
		Intent intent = getIntent();
		mDevice = (GizWifiDevice) intent.getParcelableExtra("GizWifiDevice");
		mDevice.setListener(gizWifiDeviceListener);
		Log.i("Apptest", mDevice.getDid());
	}
	public static GizWifiDevice getDevice(){
		return mDevice;
	}
	private String getDeviceName() {
		if (TextUtils.isEmpty(mDevice.getAlias())) {
			return mDevice.getProductName();
		}
		return mDevice.getAlias();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacks(mRunnable);
		// 退出页面，取消设备订阅
		mDevice.setSubscribe(false);
		mDevice.setListener(null);
		localBroadcastManager.unregisterReceiver(localReceiver);
	}


	class LocalReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent){

			Boolean i = intent.getBooleanExtra("isused",false);
			if (i){
			int data = intent.getIntExtra("kind",1);
			String key =  intent.getStringExtra("key");
			Log.d("wangtao123",key +"  "+String.valueOf(data));
				sendCommand(key,data);
			}
			else{
				Boolean data = intent.getBooleanExtra("data",true);
				String key = intent.getStringExtra("key");
				sendCommand(key,data);
			}

		}
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.btn_SheE:
			sendCommand(KEY_SHEE,true);
			Intent intent = new Intent(GosDeviceControlActivity.this,MainActivity.class);
            Bundle bundle = new Bundle();
            bundle.putParcelable("GizWifiDevice", mDevice);
            intent.putExtras(bundle);
			startActivity(intent);
			break;
		case R.id.btn_SyaE:
			sendCommand(KEY_SYAE,true);
			Intent intent1 = new Intent(GosDeviceControlActivity.this,SecendActivity.class);
            Bundle bundle1 = new Bundle();
            bundle1.putParcelable("GizWifiDevice", mDevice);
            intent1.putExtras(bundle1);
			startActivity(intent1);
			break;
		case R.id.btn_SonestartE:
			sendCommand(KEY_SONESTARTE,true);
			Intent intent3 = new Intent(GosDeviceControlActivity.this,Main1Activity.class);
            Bundle bundle3 = new Bundle();
            bundle3.putParcelable("GizWifiDevice", mDevice);
            intent3.putExtras(bundle3);
            intent3.putExtra("Stone","true");
			startActivity(intent3);
			break;
		case R.id.btn_SkindE:
			sendCommand(KEY_SKINDE,true);
			Intent intent2 = new Intent(GosDeviceControlActivity.this,Kind.class);
            Bundle bundle4 = new Bundle();
            bundle4.putParcelable("GizWifiDevice", mDevice);
            intent2.putExtras(bundle4);
			startActivityForResult(intent2,123);
			break;
			case R.id.skip:
				skip();
		default:
			break;
		}
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		switch (requestCode) {
			case 123:
				if (resultCode == RESULT_OK) {
					Log.d("Run this to","this");
					updateUI();
				}
				break;

			default:
		}
	}
	///跳转到当前状态按钮
	private void skip() {
		if(data_STATE==1){
			Toast.makeText(GosDeviceControlActivity.this,"跳转成功",Toast.LENGTH_SHORT).show();
		}
		else if(data_STATE ==2)
		{
			intent = new Intent(GosDeviceControlActivity.this,MainActivity.class);
			Bundle bundle = new Bundle();
			bundle.putParcelable("GizWifiDevice", mDevice);
			Toast.makeText(GosDeviceControlActivity.this,"跳转成功",Toast.LENGTH_SHORT).show();
			intent.putExtras(bundle);
			startActivity(intent);

		}
		else if(data_STATE ==3)
		{
			intent = new Intent(GosDeviceControlActivity.this,Main1Activity.class);
			intent.putExtra("Stone","false");
			Bundle bundle = new Bundle();
			bundle.putParcelable("GizWifiDevice", mDevice);
			Toast.makeText(GosDeviceControlActivity.this,"跳转成功",Toast.LENGTH_SHORT).show();
			intent.putExtras(bundle);
			startActivity(intent);
		}
		else if(data_STATE ==4)
		{
			intent = new Intent(GosDeviceControlActivity.this,Main1Activity.class);
			intent.putExtra("Stone","false");
			Bundle bundle = new Bundle();
			bundle.putParcelable("GizWifiDevice", mDevice);
			Toast.makeText(GosDeviceControlActivity.this,"跳转成功",Toast.LENGTH_SHORT).show();
			intent.putExtras(bundle);
			startActivity(intent);
		}
		else if(data_STATE ==5)
		{
			intent = new Intent(GosDeviceControlActivity.this,Main2Activity.class);
			Bundle bundle = new Bundle();
			bundle.putParcelable("GizWifiDevice", mDevice);
			Toast.makeText(GosDeviceControlActivity.this,"跳转成功",Toast.LENGTH_SHORT).show();
			intent.putExtras(bundle);
			startActivity(intent);
		}
		else if(data_STATE ==6)
		{
			intent = new Intent(GosDeviceControlActivity.this,Main3Activity.class);
			Bundle bundle = new Bundle();
			bundle.putParcelable("GizWifiDevice", mDevice);
			Toast.makeText(GosDeviceControlActivity.this,"跳转成功",Toast.LENGTH_SHORT).show();
			intent.putExtras(bundle);
			startActivity(intent);
		}
		else if(data_STATE ==7)
		{
			intent = new Intent(GosDeviceControlActivity.this,SecendActivity.class);
			Bundle bundle = new Bundle();
			bundle.putParcelable("GizWifiDevice", mDevice);
			Toast.makeText(GosDeviceControlActivity.this,"跳转成功",Toast.LENGTH_SHORT).show();
			intent.putExtras(bundle);
			startActivity(intent);
		}
		else if(data_STATE ==8)
		{
			intent = new Intent(GosDeviceControlActivity.this,Secend1Activity.class);
			Bundle bundle = new Bundle();
			bundle.putParcelable("GizWifiDevice", mDevice);
			Toast.makeText(GosDeviceControlActivity.this,"跳转成功",Toast.LENGTH_SHORT).show();
			intent.putExtras(bundle);
			startActivity(intent);
		}
		else if(data_STATE ==9)
		{
			intent = new Intent(GosDeviceControlActivity.this,Secend1Activity.class);
			Bundle bundle = new Bundle();
			bundle.putParcelable("GizWifiDevice", mDevice);
			Toast.makeText(GosDeviceControlActivity.this,"跳转成功",Toast.LENGTH_SHORT).show();
			intent.putExtras(bundle);
			startActivity(intent);
		}
		else if(data_STATE ==10)
		{
			intent = new Intent(GosDeviceControlActivity.this,Second2Activity.class);
			Bundle bundle = new Bundle();
			bundle.putParcelable("GizWifiDevice", mDevice);
			Toast.makeText(GosDeviceControlActivity.this,"跳转成功",Toast.LENGTH_SHORT).show();
			intent.putExtras(bundle);
			startActivity(intent);
		}
		else if(data_STATE ==11)
		{
			intent = new Intent(GosDeviceControlActivity.this,Second3Activity.class);
			Bundle bundle = new Bundle();
			bundle.putParcelable("GizWifiDevice", mDevice);
			Toast.makeText(GosDeviceControlActivity.this,"跳转成功",Toast.LENGTH_SHORT).show();
			intent.putExtras(bundle);
			startActivity(intent);
		}
		else if(data_STATE ==7)
		{
			intent = new Intent(GosDeviceControlActivity.this,Kind.class);
			Bundle bundle = new Bundle();
			bundle.putParcelable("GizWifiDevice", mDevice);
			Toast.makeText(GosDeviceControlActivity.this,"跳转成功",Toast.LENGTH_SHORT).show();
			intent.putExtras(bundle);
			startActivity(intent);
		}
	}

	/*
	 * ========================================================================
	 * EditText 点击键盘“完成”按钮方法
	 * ========================================================================
	 */
	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

		switch (v.getId()) {
		default:
			break;
		}
		hideKeyBoard();
		return false;

	}


	/**
	 * Description:根据保存的的数据点的值来更新UI
	 */
	protected void updateUI() {
		if(data_STATE == 1){
		tv_data_STATE.setText("主界面");
		}
		else if(data_STATE == 2)
			tv_data_STATE.setText("和面机界面");
		else if(data_STATE ==3)
			tv_data_STATE.setText("和面机自动停止");
		else if(data_STATE ==4){
			r1.setVisibility(View.VISIBLE);
			tv_data_STATE.setText("和面自动开始");
		}
		else if(data_STATE ==5)
			tv_data_STATE.setText("和面手动");
		else if(data_STATE ==6)
			tv_data_STATE.setText("和面配置修改");
		else if(data_STATE ==7)
			tv_data_STATE.setText("压面界面");
		else if(data_STATE ==8)
			tv_data_STATE.setText("压面自动停止");
		else if(data_STATE ==9) {
			r1.setVisibility(View.VISIBLE);
			tv_data_STATE.setText("压面自动开始");
		}
		else if(data_STATE ==10)
			tv_data_STATE.setText("压面手动");
		else if(data_STATE ==11)
			tv_data_STATE.setText("压面配置");
		else if(data_STATE ==12)
			tv_data_STATE.setText("面条种类");
		if (data_fire){
			show(this);
		}
		Log.d("面条种类",String.valueOf(data_kind));
		if (data_kind == 1){
		tv_data_kind.setText("快速面条");
		}
		if (data_kind == 2)
			tv_data_kind.setText("筋道面条");
		if (data_kind == 0)
			tv_data_kind.setText("自行配置");
		if (data_wan==1)
		tv_data_wan.setText("小碗");
		else if (data_wan ==2)
			tv_data_wan.setText("大碗");

		tv_data_hetime.setText(data_hetime+"");

	
	}


	///显示消息
	public void show(Context context){
		Bitmap btm = BitmapFactory.decodeResource(getResources(),
				R.drawable.back);
		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
				context).setSmallIcon(R.drawable.back)
				.setContentTitle("压面机系统")
				.setContentText("有火灾发生");
		mBuilder.setTicker("您有一条新消息");//第一次提示消息的时候显示在通知栏上
		mBuilder.setNumber(12);
		mBuilder.setLargeIcon(btm);
		mBuilder.setAutoCancel(true);//自己维护通知的消失


//获取通知管理器对象
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		mNotificationManager.notify(0, mBuilder.build());

	}




	/**
	 * 发送指令,下发单个数据点的命令可以用这个方法
	 * 
	 * <h3>注意</h3>
	 * <p>
	 * 下发多个数据点命令不能用这个方法多次调用，一次性多次调用这个方法会导致模组无法正确接收消息，参考方法内注释。
	 * </p>
	 * 
	 * @param key
	 *            数据点对应的标识名
	 * @param value
	 *            需要改变的值
	 */
	public void sendCommand(String key, Object value) {
		if (value == null) {
			return;
		}
		int sn = 5;
		ConcurrentHashMap<String, Object> hashMap = new ConcurrentHashMap<String, Object>();
		hashMap.put(key, value);
		// 同时下发多个数据点需要一次性在map中放置全部需要控制的key，value值
		// hashMap.put(key2, value2);
		// hashMap.put(key3, value3);
		mDevice.write(hashMap, sn);
		Log.i("liang", "下发命令：" + hashMap.toString());
	}

	private boolean isDeviceCanBeControlled() {
		return mDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceControlled;
	}

	private void toastDeviceNoReadyAndExit() {
		Toast.makeText(this, "设备无响应，请检查设备是否正常工作", Toast.LENGTH_SHORT).show();
		finish();
	}

	private void toastDeviceDisconnectAndExit() {
		Toast.makeText(GosDeviceControlActivity.this, "连接已断开", Toast.LENGTH_SHORT).show();
		finish();
	}

	/*
	 * 设备上报数据回调，此回调包括设备主动上报数据、下发控制命令成功后设备返回ACK
	 */
	@Override
	protected void didReceiveData(GizWifiErrorCode result, GizWifiDevice device,
			ConcurrentHashMap<String, Object> dataMap, int sn) {
		super.didReceiveData(result, device, dataMap, sn);
		Log.i("liang", dataMap.toString());
		if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS && dataMap.get("data") != null) {
			getDataFromReceiveDataMap(dataMap);
			mHandler.sendEmptyMessage(handler_key.UPDATE_UI.ordinal());
		}
	}

}